package com.system.dao;

import com.am.base.BaseDao;
import com.system.uitls.CommonUtil;
import com.system.uitls.IdUtils;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import net.buffalo.request.RequestContext;
import org.apache.commons.logging.Log;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class PersonDao extends BaseDao
{
  public List<Map<String, Object>> getPersonAutoData(String keyword)
  {
    keyword = keyword + "%";
    String sql = "SELECT id,name,card_num,id_card FROM sys_person WHERE (name LIKE ? OR card_num LIKE ? OR id_card LIKE ?) AND status='1'";
    return getSimpleJdbc().queryForList(sql, new Object[] { keyword, keyword, keyword });
  }

  public Map<String, String> doExport(String pix_num)
  {
    Map result = new HashMap();
    String sql = "";
    try {
      sql = "UPDATE sys_person SET type='4' WHERE num like ?";
      getSimpleJdbc().update(sql, new Object[] { pix_num + "%" });
      logger.info("PersonDao[doExport]-->sql:" + sql);
      result.put("type", "success");
      result.put("value", "设置成功");
    }
    catch (Exception ex) {
      logger.error("PersonDao[doExport]-->sql:" + sql + "\n" + ex.getMessage());
      result.put("type", "fail");
      result.put("value", "设置失败");
    }

    return result;
  }

  public Map<String, String> update(Map<String, Object> map)
  {
    String id = CommonUtil.nullToEmptyString(map.get("id"));
    String name = CommonUtil.nullToEmptyString(map.get("name"));
    String birthday = CommonUtil.nullToEmptyString(map.get("birthday"));
    String sex = CommonUtil.nullToEmptyString(map.get("sex"));
    String telephone = CommonUtil.nullToEmptyString(map.get("telephone"));
    String address = CommonUtil.nullToEmptyString(map.get("address"));
    String type = CommonUtil.nullToEmptyString(map.get("type"));
    String id_card = CommonUtil.nullToEmptyString(map.get("id_card"));
    String num = CommonUtil.nullToEmptyString(map.get("num"));
    String campus = CommonUtil.nullToEmptyString(map.get("campus"));
    String card_num = CommonUtil.nullToEmptyString(map.get("card_num"));
    String personClass = CommonUtil.nullToEmptyString(map.get("class"));
    String social_security = CommonUtil.nullToEmptyString(map.get("social_security"));
    String anamnesis = CommonUtil.nullToEmptyString(map.get("anamnesis"));
    String choose_hospital = CommonUtil.nullToEmptyString(map.get("choose_hospital"));
    String is_public_medicine = CommonUtil.nullToEmptyString(map.get("is_public_medicine"));
    String notes = CommonUtil.nullToEmptyString(map.get("notes"));
    String status = CommonUtil.nullToEmptyString(map.get("status"));

    String is_overdue = "1";
    if ((("1".equals(type)) || ("2".equals(type)) || ("3".equals(type))) && (!"".equals(card_num)))
    {
      is_overdue = "0";
    }
    if (("0".equals(type)) && (!"".equals(card_num)))
    {
      is_overdue = "0";
    }
    Map result = new HashMap();
    String sql = "";

    if ("".equals(id))
      try
      {
        id = IdUtils.getSequence(getJdbc(), "sys_person_id");

        sql = "INSERT INTO sys_person(id,name,sex,birthday,telephone,anamnesis,address,social_security,type,id_card,num,campus,card_num,class,choose_hospital,is_public_medicine,is_overdue,notes,status) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        getSimpleJdbc().update(sql, new Object[] { id, name, sex, birthday, telephone, anamnesis, address, social_security, type, id_card, num, campus, card_num, personClass, choose_hospital, is_public_medicine, is_overdue, notes, "1" });
        logger.info("PersonDao[update]-->sql:" + sql);
        result.put("type", "success");
        result.put("value", "保存成功");
      }
      catch (Exception ex) {
        logger.error("PersonDao[update]-->sql:" + sql + "\n" + ex.getMessage());
        result.put("type", "fail");
        result.put("value", "保存失败");
      }
    else {
      try
      {
        sql = "update sys_person set name=?,sex=?,birthday=?,social_security=?,anamnesis=?,telephone=?,address=?,type=?,id_card=?,num=?,campus=?,card_num=?,class=?,choose_hospital=?,is_public_medicine=?,is_overdue=?,notes=?,status=? where id=?";
        getSimpleJdbc().update(sql, new Object[] { name, sex, birthday, social_security, anamnesis, telephone, address, type, id_card, num, campus, card_num, personClass, choose_hospital, is_public_medicine, is_overdue, notes, status, id });
        logger.info("PersonDao[update]-->sql:" + sql);
        result.put("type", "success");
        result.put("value", "修改成功");
      }
      catch (Exception ex) {
        logger.error("PersonDao[update]-->sql:" + sql + "\n" + ex.getMessage());
        result.put("type", "fail");
        result.put("value", "修改失败");
      }
    }
    return result;
  }

  public Map<String, Object> getPersonById(String id)
  {
    Map result = null;
    try {
      Map configMap = getSimpleJdbc().queryForMap("SELECT date1,date2,date3,date4 FROM sys_config", new Object[0]);

      int type = 0;
      String am_startTime = CommonUtil.nullToEmptyString(configMap.get("date1"));
      String am_endTime = CommonUtil.nullToEmptyString(configMap.get("date2"));

      String pm_startTime = CommonUtil.nullToEmptyString(configMap.get("date3"));
      String pm_endTime = CommonUtil.nullToEmptyString(configMap.get("date4"));

      String currentTime = CommonUtil.getFormatCurDate("hh:MM:ss");

      int week = Calendar.getInstance().get(7);
      if ((week == 1) || (week == 7))
      {
        type = 1;
      }
      else if ((!"".equals(am_startTime)) && (!"".equals(am_endTime)))
      {
        if ((currentTime.compareTo(am_startTime) >= 0) && (currentTime.compareTo(am_endTime) <= 0))
        {
          type = 1;
        }
      }
      else if ((!"".equals(pm_startTime)) && (!"".equals(pm_endTime)))
      {
        if ((currentTime.compareTo(pm_startTime) >= 0) && (currentTime.compareTo(pm_endTime) <= 0))
        {
          type = 1;
        }

      }

      String sql = "SELECT name,sex,birthday,type,address,telephone,card_num,class,id_card,(SELECT register_amount FROM sys_cost_definition where person_type=type AND register_type=?) as register_charge,campus,social_security,anamnesis FROM sys_person WHERE id=?";
      result = getSimpleJdbc().queryForMap(sql, new Object[] { Integer.valueOf(type), id });
      result.put("register_type", Integer.valueOf(type));
    } catch (Exception ex) {
      result = new HashMap(0);
    }

    return result;
  }

  public Map<String, Object> getPersonAndAmountById(String id, String campus)
  {
    Map result = null;
    try
    {
      int type = 0;
      String currentTime = CommonUtil.getFormatCurDate("HH:MM:ss");
      int week = Calendar.getInstance().get(7);
      if ((week == 1) || (week == 7))
      {
        type = 1;
      }
      else if ("1".equals(campus)) {
        if ((currentTime.compareTo("00:00:00") >= 0) && (currentTime.compareTo("09:48:00") <= 0))
        {
          type = 1;
        }
        if ((currentTime.compareTo("11:50:00") >= 0) && (currentTime.compareTo("13:30:00") <= 0))
        {
          type = 1;
        }
        if ((currentTime.compareTo("16:50:00") >= 0) && (currentTime.compareTo("24:00:00") <= 0))
        {
          type = 1;
        }
      } else {
        if ((currentTime.compareTo("17:20:00") >= 0) && (currentTime.compareTo("21:00:00") <= 0))
        {
          type = 1;
        }
        if ((currentTime.compareTo("11:50:00") >= 0) && (currentTime.compareTo("14:50:00") <= 0))
        {
          type = 1;
        }

      }

      String sql = "SELECT name,sex,birthday,type,address,telephone,card_num,class,id_card,(SELECT register_amount FROM sys_cost_definition where person_type=type AND register_type=?) as register_charge,campus,social_security,anamnesis FROM sys_person WHERE id=?";
      result = getSimpleJdbc().queryForMap(sql, new Object[] { Integer.valueOf(type), id });
      result.put("register_type", Integer.valueOf(type));
    } catch (Exception ex) {
      result = new HashMap(0);
    }

    return result;
  }

  public Map<String, Object> modify(Map<String, Object> map)
  {
    Map result = null;
    String id = CommonUtil.nullToEmptyString(map.get("id"));
    String name = CommonUtil.nullToEmptyString(map.get("name"));
    String type = CommonUtil.nullToEmptyString(map.get("type"));
    String sex = CommonUtil.nullToEmptyString(map.get("sex"));
    String class1 = CommonUtil.nullToEmptyString(map.get("class"));
    String campus = CommonUtil.nullToEmptyString(map.get("campus"));
    String tel = CommonUtil.nullToEmptyString(map.get("tel"));
    try
    {
      String sql = "update sys_perso set name=?,sex=?,type=?,class=?,campus=?,tel=? WHERE id=?";

      result = getSimpleJdbc().queryForMap(sql, new Object[] { name, sex, type, class1, campus, tel, id });
    } catch (Exception e) {
      result = new HashMap();
    }
    return result;
  }

  public Map<String, String> importXls(String type, String filePath)
  {
    Map message = new HashMap();
    filePath = RequestContext.getContext().getServletContext().getRealPath("/WEB-INF/upload") + "/" + filePath;
    String sql = "INSERT INTO sys_person(id,num,name,sex,birthday,class,id_card,campus,is_public_medicine,status,type,is_overdue) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
    try {
      Workbook wookbook = null;
      try
      {
        wookbook = new HSSFWorkbook(new FileInputStream(filePath));
      }
      catch (Exception ex)
      {
        wookbook = new XSSFWorkbook(new FileInputStream(filePath));
      }

      Sheet sheet = wookbook.getSheetAt(0);
      int rows = sheet.getPhysicalNumberOfRows();
      List list = new ArrayList();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

      for (int i = 1; i < rows; i++)
      {
        Row row = sheet.getRow(i);
        if (row == null)
          continue;
        int cells = row.getLastCellNum();
        Object[] param = new Object[12];
        for (int j = 0; j < cells; j++)
        {
          Cell cell = row.getCell(j);
          if (cell == null) {
            continue;
          }
          switch (cell.getCellType()) {
          case 2:
            break;
          case 0:
            if (HSSFDateUtil.isCellDateFormatted(cell))
            {
              param[(j + 1)] = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
            }
            else param[(j + 1)] = Double.valueOf(cell.getNumericCellValue());

            break;
          case 1:
            param[(j + 1)] = cell.getStringCellValue();
          }

        }

        param[0] = IdUtils.getSequence(getJdbc(), "sys_person_id");

        param[9] = "1";
        param[10] = type;

        param[11] = "1";
        list.add(param);
        if (list.size() != 150)
          continue;
        getSimpleJdbc().batchUpdate(sql, list);

        list.clear();
      }

      getSimpleJdbc().batchUpdate(sql, list);
      logger.info("com.system.dao.PersonDao -->importXls 导入到数据库成功");
      message.put("type", "success");
      message.put("value", "导入成功");
    } catch (Exception e) {
      message.put("type", "fail");
      message.put("value", "导入失败");
      logger.error("com.system.dao.PersonDao -->importXls 导入到数据库失败\n" + e.getMessage());
    }

    return message;
  }

  public Map<String, String> importCardXls(String filePath)
  {
    Map message = new HashMap();
    filePath = RequestContext.getContext().getServletContext().getRealPath("/WEB-INF/upload") + "/" + filePath;
    String sql = "UPDATE sys_person SET card_num=?,is_overdue='0' WHERE id_card=?";
    try
    {
      Workbook wookbook = null;
      try
      {
        wookbook = new HSSFWorkbook(new FileInputStream(filePath));
      }
      catch (Exception ex)
      {
        wookbook = new XSSFWorkbook(new FileInputStream(filePath));
      }

      Sheet sheet = wookbook.getSheetAt(0);
      int rows = sheet.getPhysicalNumberOfRows();
      List list = new ArrayList();

      for (int i = 1; i < rows; i++)
      {
        Row row = sheet.getRow(i);
        if (row == null)
          continue;
        int cells = row.getLastCellNum();
        Object[] param = new Object[2];
        for (int j = 0; j < cells; j++)
        {
          Cell cell = row.getCell(j);
          if (cell == null) {
            continue;
          }
          switch (cell.getCellType()) {
          case 2:
            break;
          case 0:
            param[j] = Double.valueOf(cell.getNumericCellValue());
            break;
          case 1:
            param[j] = cell.getStringCellValue();
          }

        }

        list.add(param);
        if (list.size() != 150)
          continue;
        getSimpleJdbc().batchUpdate(sql, list);

        list.clear();
      }

      getSimpleJdbc().batchUpdate(sql, list);
      logger.info("com.system.dao.PersonDao -->importCardXls 导入到数据库成功");
      message.put("type", "success");
      message.put("value", "导入成功");
    } catch (Exception e) {
      message.put("type", "fail");
      message.put("value", "导入失败");
      logger.error("com.system.dao.PersonDao -->importCardXls 导入到数据库失败\n" + e.getMessage());
    }

    return message;
  }

  public Map<String, String> importMedicalDataXls(String filePath)
  {
    Map message = new HashMap();
    filePath = RequestContext.getContext().getServletContext().getRealPath("/WEB-INF/upload") + "/" + filePath;
    String sql = "UPDATE sys_person SET is_overdue='0' WHERE id_card=?";
    try
    {
      Workbook wookbook = null;
      try
      {
        wookbook = new HSSFWorkbook(new FileInputStream(filePath));
      }
      catch (Exception ex)
      {
        wookbook = new XSSFWorkbook(new FileInputStream(filePath));
      }

      Sheet sheet = wookbook.getSheetAt(0);
      int rows = sheet.getPhysicalNumberOfRows();
      List list = new ArrayList();

      for (int i = 1; i < rows; i++)
      {
        Row row = sheet.getRow(i);
        if (row == null)
          continue;
        int cells = row.getLastCellNum();
        Object[] param = new Object[1];
        for (int j = 0; j < cells; j++)
        {
          Cell cell = row.getCell(j);
          if (cell == null) {
            continue;
          }
          switch (cell.getCellType()) {
          case 2:
            break;
          case 0:
            param[j] = Double.valueOf(cell.getNumericCellValue());
            break;
          case 1:
            param[j] = cell.getStringCellValue();
          }

        }

        list.add(param);
        if (list.size() != 150)
          continue;
        getSimpleJdbc().batchUpdate(sql, list);

        list.clear();
      }

      getSimpleJdbc().batchUpdate(sql, list);
      logger.info("com.system.dao.PersonDao -->importMedicalDataXls 导入到数据库成功");
      message.put("type", "success");
      message.put("value", "导入成功");
    } catch (Exception e) {
      message.put("type", "fail");
      message.put("value", "导入失败");
      logger.error("com.system.dao.PersonDao -->importMedicalDataXls 导入到数据库失败\n" + e.getMessage());
    }

    return message;
  }

  public Map<String, String> cancelMedicalDataXls(String filePath)
  {
    Map message = new HashMap();
    filePath = RequestContext.getContext().getServletContext().getRealPath("/WEB-INF/upload") + "/" + filePath;
    String sql = "UPDATE sys_person SET is_overdue='1' WHERE id_card=?";
    try
    {
      Workbook wookbook = null;
      try
      {
        wookbook = new HSSFWorkbook(new FileInputStream(filePath));
      }
      catch (Exception ex)
      {
        wookbook = new XSSFWorkbook(new FileInputStream(filePath));
      }

      Sheet sheet = wookbook.getSheetAt(0);
      int rows = sheet.getPhysicalNumberOfRows();
      List list = new ArrayList();

      for (int i = 1; i < rows; i++)
      {
        Row row = sheet.getRow(i);
        if (row == null)
          continue;
        int cells = row.getLastCellNum();
        Object[] param = new Object[1];
        for (int j = 0; j < cells; j++)
        {
          Cell cell = row.getCell(j);
          if (cell == null) {
            continue;
          }
          switch (cell.getCellType()) {
          case 2:
            break;
          case 0:
            param[j] = Double.valueOf(cell.getNumericCellValue());
            break;
          case 1:
            param[j] = cell.getStringCellValue();
          }

        }

        list.add(param);
        if (list.size() != 150)
          continue;
        getSimpleJdbc().batchUpdate(sql, list);

        list.clear();
      }

      getSimpleJdbc().batchUpdate(sql, list);
      logger.info("com.system.dao.PersonDao -->cancelMedicalDataXls 导入到数据库成功");
      message.put("type", "success");
      message.put("value", "导入成功");
    } catch (Exception e) {
      message.put("type", "fail");
      message.put("value", "导入失败");
      logger.error("com.system.dao.PersonDao -->cancelMedicalDataXls 导入到数据库失败\n" + e.getMessage());
    }

    return message;
  }
}